#! /usr/bin/perl

use warnings;
use strict;
use Getopt::Std;
use File::Basename;
use Class::Date qw(now date);

our $VERSION = '0.02';

sub init {

	my $logged_submissions = '/var/nepenthes/log/logged_submissions';
	my $binaries           = '/var/nepenthes/binaries';
	my $institution        = 'CTI';
	my $nepenthes          = `hostname`;
	chomp($nepenthes);

	my ( %opt, $date, $yesterday );
	getopts( 'l:d:b:i:n:hr', \%opt ) or usage();
	usage() if $opt{'h'};
	
	if ( exists $opt{'r'} ){
		`rm -f *.tgz`;
	}

	local $Class::Date::DATE_FORMAT = "%F";
	$date = now;
	if ( exists $opt{'d'} ) {
		print STDERR "Date format must be YYYY-MM-DD.\n" and exit
		  if $opt{'d'} !~ /^[0-9]{4}-[0-9]{2}-[0-9]{2}$/;
		$date = date( $opt{'d'} );
	}
	$yesterday = $date - '1D';

	$logged_submissions = $opt{'l'} if $opt{'l'};
	$binaries           = $opt{'b'} if $opt{'b'};
	$institution        = $opt{'i'} if $opt{'i'};
	$nepenthes          = $opt{'n'} if $opt{'n'};

	my @teste;

	my ( $url, $file );
	my $folder = "$institution-$nepenthes\_$date";
	mkdir $folder or die "$!";
	open( SUBMISSIONS, "<",  $logged_submissions ) or die "$!";
	open( LOG,         ">>", "$folder/log.txt" )   or die "$!";
	while (<SUBMISSIONS>) {
		if ( $~ = /^\[$yesterday/ ) {
			( $url, $file ) = ( split(/\s/) )[ 4, 5 ];
			print LOG "$url $file\n";
			`cp -p "$binaries/$file" "$folder/$file"` if ! -e "$folder/$file";
		}
	}
	close(SUBMISSIONS);
	close(LOG);
	
	`tar czf "$folder.tgz" "$folder"`;
	`rm -rf $folder`;

	exit;
}

sub usage() {
	print STDERR 'This program generate a malware package from nepenthes.

Usage: '
	  . basename($0)
	  . ' [-h] [-l file] [-d date] [-b directory] [-i string] [-n string] [-r]
    -l file     : log file of nepenthes 
    -d date 	: date of package
    -b directory: malware directory from nepenthes
    -i string 	: institution name
    -n string 	: nepenthes name
    -r 			: clean all .tgz files in local folder (use with caution)
    -h          : this (help) message

Example: ' . basename($0) . " -b /var/nepenthes/binaries -d 2009-07-22\n";

	exit;
}

init();

1;

=head1 makePackage

Perl Script that create a malware package from nepenthes.

=head1 Usage

./malwarePackage.pl [-h] [-l file] [-d date] [-b directory] [-i string] [-n string]
    -l file      : log file of nepenthes 
    -d date 	  : date of package in YYYY-MM-DD format
    -b directory : malware directory from nepenthes
    -i string 	  : institution name
    -n string 	  : nepenthes name
    -r 			 : clean all .tgz files in local folder (use with caution)
    -h           : help message

=head1 Examples:

./malwarePackage.pl -b /var/nepenthes/binaries -d 2009-07-22

=head1 Requirement
	This program needs:
	
=head2 Perl Modules
	Getopt::Std
	File::Basename
	Class::Date

=head2 Shell Programs
	cp, rm, tar 	
  
=head1 AUTHOR

Andre Andrade, E<lt>andre.andrade@dssi.cti.gov.brE<gt>

=head1 COPYRIGHT AND LICENSE

Copyright (C) 2009 by Andre Andrade.

=cut